<template>
  <div class="about">
    <van-nav-bar
      :title="(msg?'修改':'上传')+'学生分数'"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form @failed="onFailed" @submit="submit">
      <van-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          v-model="form.name"
          label="姓名"
          name="name"
          placeholder="请输入姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <!-- 通过 validator 进行函数校验 -->
        <van-field
          v-model="form.gradeL"
          type="digit"
          label="理论成绩"
          name="gradeL"
          placeholder="请输入理论成绩"
          :rules="[{ validator, message: '请输入0-100的整数' }]"
        />
        <!-- 通过 validator 返回错误提示 -->
        <van-field
          v-model="form.gradeJ"
          type="digit"
          label="技能成绩"
          name="gradeJ"
          placeholder="请输入技能成绩"
          :rules="[{ validator, message: '请输入0-100的整数' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import { Notify } from 'vant';
import { reactive, toRefs } from "vue";
import { useStore } from 'vuex';
import { useRouter,useRoute } from 'vue-router';
export default {
  setup(props) {
    const { commit,state } = useStore();
    const { query } = useRoute(); // 获取路由传参信息
    const { push } = useRouter();
    const msg = state.list[query.i]; // 取到编辑的值
    const data = reactive({
      form: {
        // 表单的信息
        name: "", // 学生姓名
        gradeL: null, // 理论成绩
        gradeJ: null, // 技能成绩
      }
    });
    if (msg){
      data.form = msg;
    }
    const onFailed = () => { // 表单正则验证失败函数
      Notify({ type: 'danger', message: '表单验证未通过' });
    };
    const submit = () => { // 表单验证通过触发的函数
      if (msg){ // msg 存在代表是编辑
          commit('update',{i:query.i,value:data.form});
      } else { // msg 不存在代表是新增
         commit('saveGread',data.form);
      }
      push('/');
    }
    // 0-100 数值的规则验证
    const validator = (val) => val>=0 && val <=100;
    return {
      ...toRefs(data),
      submit,
      onFailed,
      validator,
      msg
    };
  },
};
</script>

<style lang="scss" scoped>
.about {
  height: 100%;
}
</style>
